//
//  GYDScanViewController.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/18.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import SnapKit
import AVFoundation
import SVProgressHUD
import ZBarSDK

class GYDScanViewController: UIViewController, UIGestureRecognizerDelegate {

    
    var qrcodeScanlineQrcodeImageView : UIImageView?
    var contentView :UIView?
    private lazy var coustomTitleLabel : UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
        label.font = UIFont.systemFontOfSize(18)
        label.text = "扫一扫"
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.whiteColor()
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = BASECOLOR
        setUpNavigationBar()
        navigationItem.titleView = coustomTitleLabel
        createContentView()
        beginScanQrcode()
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
        navigationController?.interactivePopGestureRecognizer?.delegate = self
        navigationController?.navigationBar.barTintColor = RGBA(0, g: 0, b: 0, a: 0.3)
        let barItem = UIBarButtonItem.appearance()
        let shadow = NSShadow()
        shadow.shadowOffset = CGSize.zero
        barItem.setTitleTextAttributes([NSForegroundColorAttributeName:ORGINCOLOR,NSFontAttributeName:UIFont.systemFontOfSize(15),NSShadowAttributeName:shadow], forState: UIControlState.Normal)
    }
    override func viewWillDisappear(animated: Bool) {
        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
        navigationController?.interactivePopGestureRecognizer?.delegate = nil
        navigationController?.navigationBar.barTintColor = RGB(255, g: 255, b: 255)
        let barItem = UIBarButtonItem.appearance()
        let shadow = NSShadow()
        shadow.shadowOffset = CGSize.zero
        barItem.setTitleTextAttributes([NSForegroundColorAttributeName:NAVTINTCOLOR,NSFontAttributeName:UIFont.systemFontOfSize(15),NSShadowAttributeName:shadow], forState: UIControlState.Normal)
        coustomTitleLabel.textColor = NAVTINTCOLOR
        if session.running {
            session.stopRunning()
        }
        super.viewWillDisappear(animated)
    }
    
    private func setUpNavigationBar() -> Void {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(GYDScanViewController.gotoBack))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "相册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(GYDScanViewController.openCamera))
    }
    @objc private func gotoBack() -> Void {
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    
    @objc private func openCamera() -> Void {
        let cameraManager = GYDCameraManager()
        cameraManager.photoSelectedBlock = { (image) -> () in
            SVProgressHUD.showWithStatus("解析中")
            let read = ZBarReaderController()
            let cgImageRef = image.CGImage
            var symbol : ZBarSymbol
            let array = read.scanImage(cgImageRef)
            SVProgressHUD.dismiss()
            if array == nil {
                let alertView = UIAlertView(title: nil, message: "未发现二维码或条形码", delegate: nil, cancelButtonTitle: "我知道了")
                alertView.show()
            }else {
                symbol = (array as! [AnyObject])[0] as! ZBarSymbol
                self.session.stopRunning()
                let str = symbol.data
                let resultVC = GYDScanResultViewController()
                resultVC.resultText = str
                self.navigationController?.pushViewController(resultVC, animated: true)
            }
        }
        cameraManager.showWithPresentWithViewController(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        coustomTitleLabel.textColor = UIColor.whiteColor()
        self.qrcodeScanlineQrcodeImageView?.frame.origin.y =  -(self.contentView?.frame.size.height)! - 10
        if !session.running {
            session.startRunning()
        }
        beginAnimation()
    }
    
    private func createContentView() -> Void {
        let contentView = UIView()
        self.contentView = contentView
        contentView.clipsToBounds = true
        contentView.backgroundColor = UIColor.clearColor()
        view.addSubview(contentView)
        contentView.snp_makeConstraints { (make) in
            make.left.equalTo(60)
            make.right.equalTo(-60)
            make.bottom.equalTo(self.view.snp_centerY).offset(50)
            make.width.equalTo(contentView.snp_height)
        }
        
        let qrcodeBorderImageView = UIImageView(image: UIImage.resizedImage("qrcode_border"))
        contentView.addSubview(qrcodeBorderImageView)
        qrcodeBorderImageView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.bottom.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
        }
        
        let SQImageView = UIImageView(image: UIImage(named: "qrcode_scanline_qrcode"))
        qrcodeScanlineQrcodeImageView = SQImageView
        
        contentView.addSubview(SQImageView)
        SQImageView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(contentView.snp_height)
            make.bottom.equalTo(contentView.snp_top).offset(10)
        }
        
        
        let label = UILabel()
        label.text = "将条形码/二维码放入框内，即可自动扫描"
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        view.addSubview(label)
        label.snp_makeConstraints { (make) in
            make.left.equalTo(60)
            make.right.equalTo(-60)
            make.top.equalTo(contentView.snp_bottom).offset(10)
            make.height.equalTo(20)
        }
    }
    
    private func beginAnimation() -> Void {
        UIView.animateWithDuration(1.5) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.qrcodeScanlineQrcodeImageView?.frame.origin.y = (self.contentView?.frame.size.height)!
        }
    }
    
    private func beginScanQrcode() -> Void {
        //1.判断输入能否添加到会话中
        if !session.canAddInput(input) {
            return
        }
        //2.判断输出能够添加到会话中
        if !session.canAddOutput(outPut) {
            return
        }
        //3.设置出入和输出到会话中
        session.addInput(input)
        session.addOutput(outPut)
        //4.设置输出能够解析的数据类型 设置数据类型要在输出对象添加到输出会话之后才能设置
        outPut.metadataObjectTypes = outPut.availableMetadataObjectTypes
        //5.设置监听输出解析到的数据
        outPut.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        //6.添加预览图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.frame = view.bounds
        
        //开始扫描
        session.startRunning()
        
    }
    
    //MARK: - 懒加载 输入输出对象
    private lazy var  input : AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        return try? AVCaptureDeviceInput(device:device)
    }()
    //会话
    private lazy var session : AVCaptureSession =  AVCaptureSession()
    
    //输出对象
    private lazy var outPut : AVCaptureMetadataOutput = {
        let out = AVCaptureMetadataOutput()
        //设置输出对象解析数据时感兴趣的区域
        let contentWidth = GYDWindowWidth - 120
        let x  = (GYDWindowHeight/2.0 - contentWidth + 50) / self.view.height
        let y = 60 / self.view.width
        let width = contentWidth / self.view.height
        let heigth = contentWidth / self.view.width
        out.rectOfInterest = CGRect(x: x, y: y, width: width, height: heigth)
        return out
    }()
    
    
    //预览
    private lazy var previewLayer : AVCaptureVideoPreviewLayer = {
        let layer  = AVCaptureVideoPreviewLayer(session: self.session)
        return layer
    }()
    
    deinit {
        print("扫描控制器死亡")
    }
}

extension GYDScanViewController : AVCaptureMetadataOutputObjectsDelegate {
    //只要扫描到结果就会调用
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        session.stopRunning()
        let str = metadataObjects.last?.stringValue
        let resultVC = GYDScanResultViewController()
        if let sss = str {
            resultVC.resultText = sss
            self.navigationController?.pushViewController(resultVC, animated: true)
        }
    }
}

